<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .wrap {
            padding: 8px;
        }

        .groups {
            margin-bottom: 10px;
        }

        .groups button {
            padding: 5px 10px;
        }

        .slide {
            width: 1100px;
            height: 600px;
            border: 1px solid #333;
            position: relative;
        }

        .slide .ball {
            width: 100px;
            height: 100px;
            background-color: pink;
            border-radius: 50%;
            position: absolute;
            left: 0px;
            top: 0;
        }
    </style>
</head>

<body>
    <!-- .wrap>(.groups>button.start*3)+(.slide>.ball) -->
    <div class="wrap">
        <div class="groups">
            <button class="start">开始</button>
            <button class="pause">暂停</button>
            <button class="back">返回</button>
        </div>
        <div class="slide">
            <div class="ball"></div>
        </div>
    </div>
</body>
<script>
    // JS运动
    // 每隔固定时间,控制元素改变其位置 

    var start = document.getElementsByClassName("start")[0];
    var pause = document.getElementsByClassName("pause")[0];
    var back = document.getElementsByClassName("back")[0];

    var ball = document.getElementsByClassName("ball")[0];

    var timer = null;


    // 正向运动 (0-1000   => 终点值大于起点值)
    start.onclick = function () {
        animate(ball, "500px");
    }


    pause.onclick = function () {
        clearInterval(timer);
    }


    // 反向运动 (1000 - 0   => 终点值 小于 起点值)
    back.onclick = function () {
        animate(ball, 0);
    }


    function animate(ele, end) {
        // var end = 1000;

        cur = ele.offsetTop;  // 当前位置 => 起始位置
        end = parseFloat(end); // 有单位 => 去单位 

        var speed = null;
        if (end > cur) { //  0 -> 1000
            speed = 10;
        } else if (end < cur) { // 1000 -> 0
            speed = -10;
        } else {
            speed = 0;
        }

        //每次移动的位移  

        clearInterval(timer);
        timer = setInterval(function () {

            if (Math.abs(ele.offsetTop - end) <= Math.abs(speed)) { //到达终点   100 -> 1000
                clearInterval(timer);
                ele.style.top = end + "px";  // 如果超出强制到达终点
            } else { // 没有到达终点再跑一次
                // 每次ele 相较于当前位置 向前/向后 加上对应的speed
                ele.style.top = (ele.offsetTop + speed) + "px";
            }

        }, 10)
    }

</script>

</html>